<template>
  <div style="position: relative;width: 100%;height: 100%;">
    <div class="p-1">
      <div class="">
        <Upload :show-upload-list="false" style="display: inline-block;" :on-success="uploadsuccess"
          action="http://127.0.0.1:7001/upload" :headers="{
            token: token
          }">
          <Button type="primary" class="mr-2">上传</Button>
        </Upload>
        <Button type="primary" class="mr-2" @click="download()">下载</Button>
        <!-- <Button type="primary" class="mr-2" @click="fxlj()">分享</Button> -->
        <!-- <Button type="primary" class="mr-2">重命名</Button> -->
        <Button type="primary" class="mr-2" @click="plsc()">批量删除</Button>
        <Input type="text" v-model="keyword" style="width: 200px" class="mr-2" placeholder="请输入关键字">
        </Input>
        <Button type="primary" class="mr-2" @click="search()">查询</Button>
        <Button type="primary" class="mr-2" @click="chongzhi()">重置</Button>
      </div>
      <div>
        <!-- <Checkbox v-model="single" :disabled="list.length == 0 ? true : false"> <span>全选</span></Checkbox> -->
      </div>
      <Tabs :value="tabvalue" @on-click="changetab">
        <TabPane label="图片" name="image"></TabPane>
        <TabPane label="视频" name="video"></TabPane>
        <TabPane label="音乐" name="audio"></TabPane>
        <TabPane label="其他" name="more"></TabPane>
      </Tabs>
    </div>

    <div class="index-list">
      <div class="border-bottom">
        <MediaList v-for="item in list" :cmm="cmm1" :checkall="checkall" :share="share1" :download="download1"
          :yulan="yulan" :shanchu="shanchu" :item="item"></MediaList>
      </div>
    </div>
    <div class="index-page">
      <!-- <Page :total="100" /> -->
    </div>
    <Modal v-model="modal" title="分享链接" @on-cancel="cancel">
      <P @click="chakan()" style="cursor: pointer;">{{ fxlj }}</P>
    </Modal>
    <Modal v-model="modal1" title="预览">
      <img :src="obj.url" v-if="obj.ext == 'image'" style="width: 100%;" alt="">
      <video style="width: 100%;" :src="obj.url" autoplay v-if="obj.ext == 'video'"></video>
    </Modal>
    <Modal v-model="modal2" title="重命名" @on-ok="okmodal" @on-cancel="cancelmodal">
      <Input type="text" placeholder="重命名" v-model="filename" />
    </Modal>
    <Modal v-model="modal3" title="提示" @on-ok="asyncOK">
      <p>是否确认删除？</p>
    </Modal>
    <Modal v-model="modal4" title="提示" @on-ok="asyncOK1">
      <p>是否确认删除？</p>
    </Modal>
  </div>
</template>
<script setup>
import JSZip from 'jszip'

import FileSaver from 'file-saver'
import { Checkbox, Col, Input, Message } from "view-ui-plus";
import { onMounted, ref } from "vue";
import MediaList from "../components/media-list.vue";
import service from "../utils/request";
import axios from 'axios';
const token = ref("")
const single = ref(false);
const filename = ref("");
const keyword = ref("");
const tabvalue = ref("image")
const fxlj = ref("");
const list = ref([

])
const okmodal = async () => {
  const res = await service.post("/updatefilename", {
    id: fileId.value,
    fileName: filename.value
  })
  console.log(res)
  if (res.code == 200) {
    modal2.value = false
    Message.success("修改成功")
    getfile()
  }


}
const shanchuid=ref("")
const asyncOK1=async()=>{
  const res = await service.post("/delete", {
    id: shanchuid.value
  });
  if (res.code == 200) {

    Message.success("删除成功")
    getfile()

  }
}
const asyncOK =async () => {
  let checkarr = [];
  list.value.forEach(el => {
    if (el.checked == true) {
      checkarr.push(el);
    }
  })

  let ids = [];
  checkarr.forEach(el => {
    ids.push(el.id)
  })
  const res = await service.post("/pldelete", {
    ids: ids
  });
  if (res.code == 200) {

    Message.success("删除成功")
    getfile()

  }
}
const cancel = () => {
  modal.value = false
}
const cancelmodal = () => {
  modal2.value = false
}
const search = () => {
  getfile()
}
const chongzhi = () => {
  keyword.value = ""
  getfile()
}
const fileId = ref("")
const cmm1 = (item) => {
  fileId.value = item.id
  filename.value = item.name
  modal2.value = true
}
const shanchu = (item) => {
  shanchuid.value=item.id

  modal4.value=true

}
const checkall = (item) => {
  console.log(item, "选中的")
  console.log(list.value, "选中的")
}
const chakan = async () => {
  const res = await service.post("/shareread", {
    file_id: fileID.value,
    sharedurl: fxlj.value
  })
  console.log(res, "res")
  window.location.href = res.data.url
}
const fileID = ref("");
const share1 = async (item) => {
  console.log(item, "item")
  const res = await service.post("/shareadd", {
    file_id: item.id
  })
  console.log(res)
  modal.value = true;
  fxlj.value = res.data
  fileID.value = item.id
}
const obj = ref({});
const yulan = (item) => {
  modal1.value = true
  obj.value = item
}
const download1 = (item) => {
  console.log(item, "item")
  window.location.href = item.url
}
const plsc = async () => {
  let checkarr = [];
  list.value.forEach(el => {
    if (el.checked == true) {
      checkarr.push(el);
    }
  })
  if (checkarr.length == 0) {
    Message.warning("请选择要删除的文件")
  } else {
modal3.value=true
  }
}
const download = () => {
  let checkarr = [];
  list.value.forEach(el => {
    if (el.checked == true) {
      checkarr.push(el);
    }
  })
  if (checkarr.length == 0) {
    Message.warning("请选择要下载的文件")
  } else {

    const zip = new JSZip()
    const promises = []
    //将文件添加到压缩包中
    checkarr.forEach((item, index) => {
      const promise = getFile(item.url).then((data) => {
        //截取后缀名（注意重命名一定要加上原来图片的后缀，否则下载出来的文件就是错误的）
        let nameList = item.url.split('.')
        let fileName = index + '.' + nameList[nameList.length - 1]
        zip.file("压缩包", data, { binary: true })//文件名、文件流、是否为二进制
      })
      promises.push(promise)
    })
    //等待所有文件添加完进行打包
    Promise.all(promises)
      .then(() => {
        zip.generateAsync({ type: 'blob' }).then((content) => {
          //利用file-saver保存文件  自定义文件名
          FileSaver.saveAs(
            content,
            new Date().getTime()
          )

        })
      })
      .catch((err) => {
        console.log(err)
        Message.warning(err || '文件压缩失败')

      })

  }

}
const getFile = (url) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer',
    })
      .then((data) => {
        resolve(data.data)
      })
      .catch((error) => {
        reject(error.toString())
      })
  })
}

const shangchuan = () => {
  modal.value = true
}
const uploadsuccess = (e) => {
  console.log(e, "eee")
  Message.success("上传成功，请刷新查看当前已用额度")
  getfile()

}
const changetab = (e) => {
  console.log(e)
  tabvalue.value = e
  getfile()
}
const getfile = async () => {
  const res = await service.post("/getfile", {
    ext: tabvalue.value,
    name: keyword.value,
  });
  console.log(res)
  list.value = res.data
}
onMounted(() => {
  token.value = JSON.parse(window.localStorage.getItem("userinfo")).token
  getfile()
})
const modal = ref(false);
const modal1 = ref(false);
const modal2 = ref(false);
const modal3 = ref(false);
const modal4 = ref(false);
</script>
<style scoped>
.p-1 {
  padding: 10px;
  box-sizing: border-box;
}

.mr-2 {
  margin-right: 10px;
}

.index-list {
  position: absolute;
  overflow-y: auto;
  left: 0;
  right: 0;
  bottom: 55px;
  top: 110px;
}

.index-page {
  position: absolute;
  bottom: 0px;
  left: 0px;
  right: 0px;
  text-align: right;
}

.border-bottom {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.flex {
  display: flex;
  align-items: center;
}
</style>